package com.yayan.beautyclub.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value="/upload")
public class UploadController {

	private MultipartFile titlePic = null;
	/**
	 * 后台管理，图片上传
	 * @param pic
	 * @param request
	 * @param response
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value="/uploadPic.do")
	@ResponseBody
	public void uploadPic(MultipartFile pic, HttpServletRequest request, 
			HttpServletResponse response) throws IllegalStateException, IOException {
		JSONObject jsonObject = new JSONObject();		
		try {
			// 获取图片原始文件名
			String originalFilename = pic.getOriginalFilename();
			// 文件名使用当前时间
			String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			// 获取上传图片的扩展名(jpg/png/...)
			String extension = FilenameUtils.getExtension(originalFilename);
			if(pic.getSize() >= 5242880){
				jsonObject.put("status", false);
				jsonObject.put("msg", "图片大小不能超过5M");
			}else if(extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("png")
				|| extension.equalsIgnoreCase("jpeg")){
				// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
				String path = name + originalFilename;
				if(path.length() > 50)
					path = name + originalFilename.substring(originalFilename.length()-40+name.length(), originalFilename.length());
				// 图片上传的绝对路径
				String url = request.getSession().getServletContext().getRealPath("") + "upload/" + path;
				//System.out.println(url);
				File dir = new File(url);
				if(!dir.exists()) {
					dir.mkdirs();
				}
				titlePic = pic;
				// 上传图片
				pic.transferTo(new File(url));				
				jsonObject.put("status", true);
				// 将图片路径回传到浏览器
				jsonObject.put("msg", path);				
			}else{
				//图片格式不正确，返回提示信息
				jsonObject.put("status", false);
				jsonObject.put("msg", "上传图片格式必须是jpg/png/jpeg");
			}
					
		} catch (Exception e) {
			jsonObject.put("status", false);
			jsonObject.put("msg", "服务器繁忙，上传图片失败");
			throw new RuntimeException("服务器繁忙，上传图片失败");
		}
		// 设置响应数据的类型json
		response.setContentType("application/json; charset=utf-8");
		// 写回
		response.getWriter().write(jsonObject.toString());	
	}
}
